<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class UploadController extends Controller
{
    private $dir = '';  //保存目录
    private $filename = '';  //文件名称
    private $file = '';  //文件
    private $text = '';  //水印文字
    private $rotate = 0;  //逆时针旋转度数
    private $aspect_ratio = 0;    //高宽比
    private $size_max = 0;    //上传base64图片大小限制,单位：kb
    private $text_x = 100;    //文字显示位置x
    private $disk = 'images';    //保存目录
    private $extension = '';    //保存目录

    public function render($type, $params = []) {
        //        $type = request()->type;
        $types = ['img'];
        if(!in_array($type, $types)) {
            return '类型错误';
        }
        $this->initparams($params);
        return $this->$type();
    }

    private function rtdata($code = 1, $msg = '', $data = []) {
        return ['code' => $code, 'msg' => $msg, 'data' => $data];
    }

    private function initparams($params) {
        if(!isset($params['dir'])) {
            return $this->rtdata(0, '未指定存储目录');
        }
        //文件验证
        if(!isset($params['file'])) {
            return $this->rtdata(0, '文件验证失败');
        }
        $this->dir = $params['dir'];
        //文件名称
        $filename = array_get($params,'filename',time());
        $this->extension = pathinfo($filename,PATHINFO_EXTENSION);
        $this->filename = substr($filename,0,-(strlen($this->extension)+1));
        // dd($this->filename);
        $this->file = $params['file'];
        $this->text = array_get($params,'text','');
        $this->isRotate($this->file, array_get($params,'rotate',0));
        $this->aspect_ratio = array_get($params,'aspect_ratio',0);
        $this->size_max = array_get($params,'size_max',0);
        $this->text_x = array_get($params,'text_x',100);
        $this->disk = array_get($params,'disk','images');
    }

    //base64图片上传
    private function img() {
        $file = $this->file;
        if(!$file){
            return rtdata(0,'文件出错！');
        }
        $disk = Storage::disk($this->disk);
        $size_max = $this->size_max;
        if(is_string($file)){
            $base64_img = $file;
            preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $res);
            $base64_img = str_replace($res[1], '', $base64_img);
            if($size_max > 0){
                $img_len = strlen($base64_img);
                $file_size = intval($img_len - ($img_len/8)*2);
                $file_size = number_format(($file_size/1024),2);
                if($file_size > $size_max){
                    return $this->rtdata(0, "图片不能超过{$size_max}KB,您的图片大小为{$file_size}KB");
                }
            }
            $file = base64_decode($base64_img);
        }else{
            if($size_max > 0){
                $file_size = $file->getClientSize();
                $file_size = number_format(($file_size/1024),2);
                if($file_size > $size_max){
                    return $this->rtdata(0, "图片不能超过{$size_max}KB,您的图片大小为{$file_size}KB");
                }
            }
            $file = file_get_contents($file);
        }
        $tmppath = $this->dir.'/temp/'.$this->filename.'.'. ($this->extension ?: 'png');
        $disk->put($tmppath, $file);
        try {
            $file = $disk->path($tmppath);
            $png = Image::make($file);
        } catch(\Exception $e) {
            $disk->delete($tmppath);
            return rtdata(0,'请检查图片数据！');
        }
        $aspect_ratio = $this->aspect_ratio;
        if($aspect_ratio) {
            $width = $png->getWidth();
            $height = $png->getHeight();
            $whr = ceil($width/$height*100)/100;
            $hwr = ceil($height/$width*100)/100;
            $r1 = $whr < ($aspect_ratio + 0.3) && $whr > ($aspect_ratio - 0.3);
            $r2 = $hwr < ($aspect_ratio + 0.3) && $hwr > ($aspect_ratio - 0.3); 
            // dd($whr,$hwr, $aspect_ratio,$r1,$r2);
            if(!$r1 && !$r2)  {
                return $this->rtdata(0, '图片尺寸不符合要求');
            }
        }
        //旋转
        $this->rotate ? $png->rotate(90) : '';
        //缩放
        $size = $disk->size($tmppath);
        if($size > 100*1024) {
            $png->heighten(600);
        }

        $fontPath = public_path('font/ARIAL_1.TTF');
        if($this->text){
            // $text = $this->to_unicode($this->text);
            $text = $this->text;
            $png->text($text, $this->text_x, 10, function($font) use ($fontPath) {
                $font->file($fontPath);  //设置字体文件的路径或 GD 库内部字体，范围 1 到 5 之间的整数值，默认值 1
                $font->size(30);
                $font->color('#ff0000');
                $font->align('center');
                $font->valign('top');
            });
        }
        $png->encode('png', 100);
        $filename = $this->dir.'/'.$this->filename.'.png';
        $disk->exists($filename) ? $disk->delete($filename) : '';  //判断删除再存放
        $bool = $disk->put($filename, $png);    //保存图片
        $disk->exists($tmppath) ? $disk->delete($tmppath) : '';
        if($bool) {
            $path = $disk->url($filename);   //保存路径
            return $this->rtdata(1, '图片上传成功', ['path' => $path]);
        }
        unset($png);
        return $this->rtdata(0, '图片上传失败');
    }

    private function isRotate($file, $rotate) {
        try{
            $fileinfo = getimagesize($file);
            $width = $fileinfo[0];
            $height = $fileinfo[1];
            $this->rotate = $height > $width ? 1 : 0;
        }catch(\Exception $exception){

        }
            
    }

    //解决中文乱码问题（将 utf-8 字符串转为 Unicode 编码格式）
    private function to_unicode($string){
        $str = mb_convert_encoding($string, 'UCS-2', 'UTF-8');
        $arrstr = str_split($str, 2);
        $unistr = '';
        foreach ($arrstr as $n) {
            $dec = hexdec(bin2hex($n));
            $unistr .= '&#' . $dec . ';';
        }
        return $unistr;
    }

    /**
    * php GD库生成折线图、柱状图、饼状图
    */
    private function gd($y_name,$shuju,$path){
        $img_gao=170;
        $img_kuan=0;
        $jiange=30;//横坐标点与点之间的间隔，生成的图片宽度会根据传入数据的多少而自动变化
        $zuo=20;//左侧留空
        $you=20;//右侧留空
        $shang=20;//上留空
        $xia=20;//下留空
        $zuidashujuzhi=1;
        $p_x = array();//点横坐标
        $p_y = array();//点纵坐标
        $y_name=explode(",",$y_name);
        $shuju=explode(",",$shuju);
        //得到纵轴最大值
        for ($i=0; $i < count($shuju); $i++) { 
            if($shuju[$i] > $zuidashujuzhi){
                $zuidashujuzhi=$shuju[$i];
            }
        }
        //得到图像宽度
        $img_kuan=$zuo+$you+count($shuju)*$jiange;
        //然后创建图像资源
        $image = imagecreate($img_kuan,$img_gao);

        //灰色背景
        $white = imagecolorallocate($image, 0xEE, 0xEE, 0xEE);
        //坐标轴用黑色显示
        $zuobiao_yanse = imagecolorallocate($image, 0x00, 0x00, 0x00);
        //折线用蓝色显示
        $xian_yanse = imagecolorallocate($image, 0x00, 0x00, 0xFF);
        //画坐标
        //横轴
        imageline ( $image, $zuo, $img_gao-$xia, $img_kuan-$you/2, $img_gao-$xia, $zuobiao_yanse);
        //纵轴
        imageline ( $image, $zuo, $shang/2, $zuo, $img_gao-$xia, $zuobiao_yanse);
        //得到每个点的坐标
        for($i=0;$i<count($shuju);$i++){
            array_push($p_x, $zuo+$i*$jiange);
            array_push($p_y, $shang+round(($img_gao-$shang-$xia)*(1-$shuju[$i]/$zuidashujuzhi)));
        }
        //纵轴刻度
        imageline ( $image, $zuo, $shang, $zuo+6, $shang, $zuobiao_yanse);
        imagestring ( $image, 1, $zuo/4, $shang,$zuidashujuzhi, $zuobiao_yanse);
        imageline ( $image, $zuo, $shang+($img_gao-$shang-$xia)*1/4, $zuo+6, $shang+($img_gao-$shang-$xia)*1/4, $zuobiao_yanse);
        imagestring ( $image, 1, $zuo/4, $shang+($img_gao-$shang-$xia)*1/4,$zuidashujuzhi*3/4, $zuobiao_yanse);
        imageline ( $image, $zuo, $shang+($img_gao-$shang-$xia)*2/4, $zuo+6, $shang+($img_gao-$shang-$xia)*2/4, $zuobiao_yanse);
        imagestring ( $image, 1, $zuo/4, $shang+($img_gao-$shang-$xia)*2/4,$zuidashujuzhi*2/4, $zuobiao_yanse);
        imageline ( $image, $zuo, $shang+($img_gao-$shang-$xia)*3/4, $zuo+6, $shang+($img_gao-$shang-$xia)*3/4, $zuobiao_yanse);
        imagestring ( $image, 1, $zuo/4, $shang+($img_gao-$shang-$xia)*3/4,$zuidashujuzhi*1/4, $zuobiao_yanse);
        //横轴刻度
        for($i=0;$i<count($shuju);$i++){
            imageline ( $image, $zuo+$i*$jiange, $img_gao-$xia, $zuo+$i*$jiange, $img_gao-$xia-6, $zuobiao_yanse);
            imagestring ( $image, 1, $zuo+$i*$jiange-$jiange/4, $shang+($img_gao-$shang-$xia)+2,$y_name[$i], $zuobiao_yanse);
        }

        //折线
        $shuju_yanse_int=0;
        for ($i=0; $i < count($shuju); $i++) {
            if($i+1 <> count($shuju)){
        imageline($image,$p_x[$i],$p_y[$i],$p_x[$i+1],$p_y[$i+1],$xian_yanse);
        imagefilledrectangle($image, $p_x[$i]-1, $p_y[$i]-1, $p_x[$i]+1, $p_y[$i]+1, $xian_yanse);
            }
        }
        //上一个循环没有画出最后一个点效果，这里还要追加
        imagefilledrectangle($image, $p_x[count($shuju)-1]-1, $p_y[count($shuju)-1]-1, $p_x[count($shuju)-1]+1, $p_y[count($shuju)-1]+1, $xian_yanse);

        //标注数据值
        for($i=0;$i<count($shuju);$i++){
            imagestring ( $image, 3, $p_x[$i]+4, $p_y[$i]-12,$shuju[$i], $zuobiao_yanse);
        }

        // //设定文件头,输出文件
        // header('Content-type: image/png');
        // //输出图像
        // imagepng($image);
        // //释放资源
        // imagedestroy($image);

        //输出图像
        imagepng($image,$path);
        //释放资源
        imagedestroy($image);
    }
}
